package com.cus.tom.transfer.ac;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;

import androidx.annotation.Nullable;

import com.cus.tom.transfer.App;
import com.cus.tom.transfer.bean.Const;
import com.cus.tom.transfer.databinding.ActCodeBinding;
import com.cus.tom.transfer.frag.BaseDialogFragment;
import com.cus.tom.transfer.frag.TipDlg;
import com.cus.tom.transfer.trans.service.SendService;
import com.cus.tom.transfer.utils.Read;
import com.cus.tom.transfer.utils.ToastUtil;
import com.cus.tom.transfer.utils.Utils;
import com.hjq.permissions.OnPermissionPageCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.jwsd.libzxing.QRCodeManager;
import com.plata.base.aclr.utils.NetworkUtils;
import com.plata.base.base.CommonUtil;

import org.json.JSONObject;

public class CodeAct extends BaseAct {
    ActCodeBinding binding;

    BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Intent i = new Intent(context, SendAct.class);
            i.putExtra("type", 0);
            startActivity(i);
            exit(false);
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActCodeBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        binding.back.setOnClickListener(v -> exit(true));

        if (!NetworkUtils.isWifi(this)) {
            ToastUtil.showShortToast(this, "请连接WIFI");
            exit(false);
            return;
        }

        registerReceiver(receiver, new IntentFilter(Const.SEND_START));

        int w = Utils.dp2Px(this, 200);
        String str = getHost();
        if (TextUtils.isEmpty(str)) {
            ToastUtil.showShortToast(this, "二维码生成失败");
            exit(false);
            return;
        }
        Bitmap bm = QRCodeManager.getInstance().createQRCode(str, w, w);
        binding.img.setImageBitmap(bm);

        if (!notificationEnable()) {
            TipDlg dlg = new TipDlg().setMsg("需要授予通知权限，以便通知您发送和接收进度");
            dlg.setOnDismissListener(new BaseDialogFragment.OnDismissListener() {
                @Override
                public void onDismiss(boolean isOk, Object value) {
                    if (isOk) {
                        XXPermissions.startPermissionActivity(
                                CodeAct.this, Permission.POST_NOTIFICATIONS, new OnPermissionPageCallback() {
                                    @Override
                                    public void onGranted() {
                                        startService();
                                    }

                                    @Override
                                    public void onDenied() {
                                        startService();
                                    }
                                });
                    } else {
                        startService();
                    }
                }
            });
            dlg.show(getSupportFragmentManager(), "");
        } else {
            startService();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            exit(true);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private boolean notificationEnable() {
        boolean bo = Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU || XXPermissions.isGranted(this, Permission.POST_NOTIFICATIONS);
        return bo;
    }

    private void exit(boolean stop) {
        try {
            unregisterReceiver(receiver);
            if (!stop) {
                return;
            }
            Intent intent = new Intent(this, SendService.class);
            intent.setAction("cancel");
            startService(intent);
        } finally {
            finish();
        }
    }

    private void startService() {
        Intent startIntent = getIntent();
        Intent intent = new Intent(this, SendService.class);
        if (Intent.ACTION_SEND.equals(startIntent.getAction()) ||
                Intent.ACTION_SEND_MULTIPLE.equals(startIntent.getAction())) {
            intent.setAction(startIntent.getAction());
            intent.setData(startIntent.getParcelableExtra(Intent.EXTRA_STREAM));
        } else {
            intent.setData(startIntent.getData());
            intent.putExtra("set", startIntent.getSerializableExtra("set"));
            intent.putStringArrayListExtra("files", startIntent.getStringArrayListExtra("files"));
        }
        startForegroundServiceCompat(intent);
    }

    public String getHost() {
        try {
            JSONObject obj = new JSONObject();
            obj.put("id", Read.getWifiId(this));
            obj.put("address", CommonUtil.getIpAddress(App.getApp()));
            obj.put("port", Const.TCP_PORT);
            return obj.toString();
        } catch (Throwable e) {
            e.printStackTrace();
            return "";
        }
    }

    private void startForegroundServiceCompat(Intent intent) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startForegroundService(intent);
        } else {
            startService(intent);
        }
    }
}
